package com.card.manager.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.card.framework.page.model.PageModel;
import com.card.framework.util.CommonUtil;
import com.card.framework.util.TreeBulid;
import com.card.manager.domain.Resources;
import com.card.manager.domain.Roles;
import com.card.manager.services.ResourcesService;

@Controller
@RequestMapping("/resources")
public class ResourcesController {
	final static Logger logger = Logger.getLogger(ResourcesController.class);
	@Autowired(required=true) 
	private TreeBulid treeBulid;
	@Autowired(required=true) 
	private ResourcesService resourcesServices;
	@InitBinder
	public void setupDataBinder(WebDataBinder dataBinder) {
		//表单页面如果有时间类型的需要initbinder
		dataBinder.registerCustomEditor(String.class,new StringTrimmerEditor(false));  
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	@RequestMapping(value="/index")
	public String index(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws Exception{
		return "resourcesList";
	}
	@RequestMapping(value="/queryList",method=RequestMethod.POST)
	@ResponseBody
	public List<Resources> queryList(HttpServletRequest request) throws Exception{
		String id = request.getParameter("ignId");
		List<Resources> list = null;
		if(StringUtils.isNotBlank(id)){
			list = resourcesServices.getAllEnabledResourcesNotInclude(Integer.parseInt(id));
		}else{
			list = resourcesServices.getAllEnabledResources();
		}
		
		return buildTree(list);
	}
	@SuppressWarnings("unused")
	private List<Resources> buildTree(List<Resources> list){
		List<Resources> rootElement = new ArrayList<Resources>();
		Map<Integer,List<Resources>> allElement = new LinkedHashMap<Integer,List<Resources>>();
		for(Resources r : list){
			if(r.getParentid() == -2){
				r.setId(r.getResouceid());
				r.setText(r.getName());
				rootElement.add(r);
			}else{
				List<Resources> set = allElement.get(r.getParentid());
				if(set == null){
					set = new ArrayList<Resources>();
				}
				r.setId(r.getResouceid());
				r.setText(r.getName());
				set.add(r);
				allElement.put(r.getParentid(),set);
			}
		}
		Map<String,Object> map = new LinkedHashMap<String,Object>();
		Collections.sort(rootElement, new Comparator<Resources>(){
			public int compare(Resources o1, Resources o2) {
				return o1.getOrdernum() - o2.getOrdernum();
			}
		});
		for(Resources pc : rootElement){
			pc.setChildren(getSub(pc.getResouceid(),allElement));
		}
		return rootElement;
	}
	private List<Resources> getSub(Integer id,Map<Integer,List<Resources>> map){
		List<Resources> list = map.get(id);
		if(list != null && list.size() > 0){
			Collections.sort(list, new Comparator<Resources>(){
				public int compare(Resources o1, Resources o2) {
					return o1.getOrdernum() - o2.getOrdernum();
				}
			});
			for(Resources pc : list){
				pc.setChildren(getSub(pc.getResouceid(),map));
			}
		}
		return list;
	}
	
	
	
	@RequestMapping("/addResourcesPopWindow")
	public String add(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		Resources resource = new Resources();
		resource.setEnable((byte)1);
		resource.setDelflg((byte)1);
		resource.setOrdernum(0);
		SecurityContext sc = (SecurityContext)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		resource.setCreatuserid(sc.getAuthentication().getName());
		String pid = request.getParameter("pid");
		resource.setParentid(Integer.parseInt(pid));
		request.setAttribute("resource",resource);
		return "/resourcesPopWindow";
	}
	
	@RequestMapping(value="/resourcesAdd",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> resourcesAdd(Resources resource){
		Map<String, String> map = new HashMap<String, String>();
		try {
			resourcesServices.add(resource);
			map.put("mes", "操作成功");
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
			logger.error("addOrUpdate", e);
		}
		return map; 
	}
	
	@RequestMapping("/updateResourcesPopWindow")
	public String update(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		Resources resource = resourcesServices.getById(Integer.parseInt(id));
		request.setAttribute("resource",resource);
		return "/resourcesPopWindow";
	}
	
	@RequestMapping(value="/resourcesUpdate",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> resourcesUpdate(Resources resource){
		Map<String, String> map = new HashMap<String, String>();
		try {
			resourcesServices.update(resource);
			map.put("mes", "操作成功");
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
			logger.error("addOrUpdate", e);
		}
		return map; 
	}
	
	@RequestMapping(value="/initResourcesIdPath")
	@ResponseBody
	public Map<String, String> initResourcesIdPath(){
		Map<String, String> map = new HashMap<String, String>();
		try {
			resourcesServices.updateIdPath();
			map.put("mes", "操作成功");
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
			logger.error("addOrUpdate", e);
		}
		return map; 
	}
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> delete(@RequestParam("id")Integer id){
		Map<String, String> map = new HashMap<String, String>();
		try {
			resourcesServices.delete(id);
			map.put("mes", "操作成功");
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
			logger.error("addOrUpdate", e);
		}
		return map; 
	}
//	/**
//	 * 提交新增或修改,根据id是否为空判断.
//	 * 返回提交成功后的数据.json格式
//	 */
//	@RequestMapping(value="/roleUpdate",method=RequestMethod.POST)
//	@ResponseBody
//	public Map<String, String> roleUpdate(HttpServletRequest request,Roles role) throws Exception{
//		Map<String, String> map = new HashMap<String, String>();
//		try { 
//			if(role.getRoleid() == null){
//				if(!roleServices.isExistName(role.getName())){
//					roleServices.add(role);
//					map.put("result", "succ");
//				}else{
//					map.put("result", "fail");
//					map.put("reason", "exists");
//				}
//			}else{
//				roleServices.update(role);
//				map.put("result", "succ");
//			}
//		}
//		catch (Throwable e) {
//			CommonUtil.throwsException(map, e);
//		}
//		return map; 
//	}
//	/**
//	 * 提交新增或修改,根据id是否为空判断.
//	 * 返回提交成功后的数据.json格式
//	 */
//	@RequestMapping(value="/roleAdd",method=RequestMethod.POST)
//	@ResponseBody
//	public Map<String, String> roleAdd(HttpServletRequest request,Roles role) throws Exception{
//		Map<String, String> map = new HashMap<String, String>();
//		try { 
//			if(role.getRoleid() == null){
//				if(!roleServices.isExistName(role.getName())){
//					roleServices.add(role);
//					map.put("result", "succ");
//				}else{
//					map.put("result", "fail");
//					map.put("reason", "exists");
//				}
//			}else{
//				roleServices.update(role);
//				map.put("result", "succ");
//			}
//		}
//		catch (Throwable e) {
//			CommonUtil.throwsException(map, e);
//		}
//		return map; 
//	}
//	
//	@RequestMapping(value="/delete",method=RequestMethod.POST)
//	@ResponseBody
//	public Map<String, String> delete(@RequestParam("json") String json){
//		Map<String, String> map = new HashMap<String, String>();
//		try {
//			roleServices.deleteRoles(CommonUtil.getBean(json, Roles.class));
//			map.put("mes", "删除成功");
//		} catch (Throwable e) {
//			CommonUtil.throwsException(map, e);
//		}
//		return map;//重定向
//	}
//	@RequestMapping("/setResource")
//	public String setResource(HttpServletRequest request,@RequestParam("roleid")Integer roleid){
//		request.setAttribute("roleid",roleid);
//		return "/roleSetResources";
//	}
//	@RequestMapping("/loadResources")
//	@ResponseBody
//	public String loadResources(HttpServletRequest request,@RequestParam("roleid")Integer roleid){
//		return treeBulid.buildAllTree(roleid,2,-2);
//	}
//	@RequestMapping(value="/saveResources",method=RequestMethod.POST)
//	@ResponseBody
//	public Map<String, String> saveResources(HttpServletRequest request,@RequestParam("roleid")Integer roleid,@RequestParam("resid")Integer[] resid) throws Exception{
//		Map<String, String> map = new HashMap<String, String>();
//		
//		try {
//			roleServices.saveRoleResource(roleid, resid);
//			MySecurityMetadataSource.resourceMap = roleServices.loadResources();
//			map.put("result", "succ");
//		}
//		catch (Throwable e) {
//			e.printStackTrace();
//			CommonUtil.throwsException(map, e);
//		}
//		return map; 
//	}
//	@SuppressWarnings("unused")
//	private List<Map<String,Object>> buildTree(List<Resources> list,List<Resources> roleList){
//		List<Map<String,Object>> rootElement = new ArrayList<Map<String,Object>>();
//		Map<Integer,List<Map<String,Object>>> allElement = new LinkedHashMap<Integer,List<Map<String,Object>>>();
//		for(Resources r : list){
//			if(r.getParentid() == -1){
//				Map<String,Object> obj = new HashMap<String,Object>();
//				obj.put("id",r.getResouceid());
//				obj.put("text",r.getName());
//				obj.put("checked",roleList.contains(r));
//				obj.put("state","opened");
//				obj.put("iconCls","icon-computer");
//				rootElement.add(obj);
//			}else{
//				List<Map<String,Object>> set = allElement.get(r.getParentid());
//				if(set == null){
//					set = new ArrayList<Map<String,Object>>();
//				}
//				Map<String,Object> obj = new HashMap<String,Object>();
//				obj.put("id",r.getResouceid());
//				obj.put("text",r.getName());
//				obj.put("checked",roleList.contains(r));
//				obj.put("state","closed");
//				set.add(obj);
//				allElement.put(r.getParentid(),set);
//			}
//		}
//		Map<String,Object> map = new LinkedHashMap<String,Object>();
////		Collections.sort(rootElement, new Comparator<Map<String,Object>>(){
////			public int compare(Map<String,Object> o1, Map<String,Object> o2) {
////				return (Integer)o1.get("order") - (Integer)o2.get("order");
////			}
////		});
//		for(Map<String,Object> pc : rootElement){
//			pc.put("children", getSub((Integer)pc.get("id"),allElement));
//		}
//		return rootElement;
//	}
//	private List<Map<String,Object>> getSub(Integer id,Map<Integer,List<Map<String,Object>>> map){
//		List<Map<String,Object>> list = map.get(id);
//		if(list != null && list.size() > 0){
////			Collections.sort(list, new Comparator<Map<String,Object>>(){
////				public int compare(Map<String,Object> o1, Map<String,Object> o2) {
////					return (Integer)o1.get("order") - (Integer)o2.get("order");
////				}
////			});
//			for(Map<String,Object> pc : list){
//				pc.put("children", getSub((Integer)pc.get("id"),map));
//			}
//		}
//		return list;
//	}
}
